
//tslint:disable
import { Injectable } from '@angular/core';
import { EventService } from 'src/app/shared/service/event.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { MapBaiduService } from 'src/app/shared/service/map.baiduapi';
import { HttpService } from 'src/app/shared/service/http.service';
import { IndexedDBService } from 'src/app/shared/service/indexed-db.service';
import { ChatService } from 'src/app/shared/service/chatService';
import { PageModalService } from 'src/app/shared/service/page-modal-service';
import { JPush } from "@jiguang-ionic/jpush/ngx";
import { Platform, ModalController } from '@ionic/angular';
@Injectable({
    providedIn: 'root'
})
export class ProcessLoginDataService {
    constructor(
        public eventService: EventService,
        public appGlobalService: AppGlobalService,
        public mapBaiduService: MapBaiduService,
        public indexedDBService: IndexedDBService,
        public pageModalService: PageModalService,
        public modalCtrl: ModalController,
        public webSocketTalk: ChatService,
        public jPush: JPush,
        public http: HttpService,
        private platform: Platform

    ) {
        // this.isPreView = false;
    }

    public async processLoginData(res: any, mobile: any, params) {
        try {

            const that = this;
            // 删除已经注册的刷新event
            this.eventService.eventEmit.removeAllListeners("clearlistTagRefreshTime");
            // 处理 员工 当前定位城市
            if (res.data.position) {
                this.setPxwCityPosition(res.data.position);
            }
            // 2024.07.09 初始化临时全局变量
            that.appGlobalService.initTemporaryVariables();
            // 处理登录账号信息
            if (res.data.user_id) {
                localStorage.setItem("userId", res.data.user_id);
                localStorage.setItem("loginAccount", mobile);
                this.platform.ready().then(() => {
                    // 只有手机端才会发起极光s设置别名
                    if (localStorage.getItem('client') !== 'BROWSER' && (this.platform.is('ios') || this.platform.is('android'))) {
                        this.appGlobalService.initUmengEventWithParameters("enter_app_with_loginAccount_event");
                        this.jPush
                            .setAlias({
                                sequence: 1,
                                alias: this.appGlobalService.pushAlias + mobile
                            })
                            .then(
                                result => {
                                    const sequence = result.sequence;
                                    const alias = result.alias;
                                    console.log("设置别名成功：" + alias);
                                },
                                error => {
                                    const sequence = error.sequence;
                                    const errorCode = error.code;
                                    console.log("设置别名失败：" + errorCode);
                                }
                            );
                    }
                });
                this.http.get(
                    "message/userinfo/im/" + res.data.user_id,
                    response => {
                        const data = response.data;
                        if (res.data.user_id.includes('random')) {
                            data.nickname = '访客';
                        }
                        if (data.nickname) {
                            this.appGlobalService.currentNickName = data.nickname;
                            localStorage.setItem('currentNickName', data.nickname);
                        }
                        if (data.avatar_url === null) { // 没头像给默认头像
                            data.avatar_url = this.appGlobalService.defaultImg;
                        }
                        if (data.avatar_url) {
                            this.appGlobalService.getBase64Str(data.avatar_url + "?x-oss-process=image/resize,h_36", str => {
                                localStorage.setItem('currentAvatarStr', str);
                                that.webSocketTalk.setAvatar(res.data.user_id, str);
                            });
                            this.appGlobalService.currentAvatarUrl = data.avatar_url;
                            localStorage.setItem('currentAvatarUrl', data.avatar_url);
                        }
                        localStorage.setItem('currentWorkMobile', data.work_mobile);
                        // 2024.08.02 联调接口返回参数
                        if (res.data.shopGoodsCartCount) {
                            // tslint:disable-next-line:no-string-literal
                            data['shopGoodsCartCount'] = res.data.shopGoodsCartCount;
                        }
                        that.webSocketTalk.currentUserObj = data;
                        this.indexedDBService.putByKeyCallbak(data, res.data.user_id, "user", () => {
                            if (res.data.shopGoodsCartCount) {
                                that.webSocketTalk.setCartItemCount(res.data.shopGoodsCartCount);
                            }
                        });
                    },
                    error => {
                        console.log("msg-----> error:" + JSON.stringify(error));
                    }
                );
                // websocket链接
                this.webSocketTalk.connectting(localStorage.getItem("userId"), true, (eData) => {
                    this.appGlobalService.consoleLog('  建立ws连接  ', '  	   ');
                });
                // this.webSocketTalk.checkAndLoadChatData();
                if (this.appGlobalService.clientType === 'pxw') {
                    localStorage.setItem('startRefreshTimerTag', '1');
                    this.eventService.eventEmit.emit("startRefreshTimer");
                }
            }

            // 登录成功后发现 alert 2s后跳转
            if (res.data.alert) {
                setTimeout(() => {
                    const link = {
                        params: res.data.alert.params,
                        target: res.data.alert.target,
                        type: 'pageModal'
                    };
                    this.pageModalService.openPage(link);
                }, 2000);
            }


            localStorage.setItem("loginStatus", "true");
            this.appGlobalService.loginStatus = true;
            localStorage.setItem("needRefreshTab1", "true");
            localStorage.setItem("needRefreshTab2", "true");
            localStorage.setItem("needRefreshTab3", "true");
            localStorage.setItem("needRefreshTab4", "true");
            localStorage.setItem("needRefreshTab5", "true");


            if (localStorage.getItem("useTarget") === "true") {
                const cityId = JSON.parse(localStorage.getItem("position"))
                    ? JSON.parse(localStorage.getItem("position")).code
                    : 4403;
                const pageParams = {
                    pageId: res.target,
                    params: {
                        code: cityId
                    },
                    sessionId: localStorage.getItem("sessionId")
                };
                this.appGlobalService.goToForward(pageParams);
                localStorage.removeItem("useTarget");
            } else {
                // 12.09 新增登录参数联调
                if (params
                    && params.content
                    && params.content.stayCurrentPage === 'true') {
                        const modal = this.modalCtrl.getTop();
                        if (modal) {
                            (await modal).dismiss('success');
                        }
                        return;
                }
                const skip = res.skip;
                if (skip && skip === 1) {
                    // "是否跳转页面 0不跳/1跳"
                    const pageParams = {
                        target: res.target,
                        params: res.params,
                        type: "page",
                        sessionId: localStorage.getItem("sessionId")
                    };
                    if (res.params && res.params && res.params.pageType) {
                        // // 关闭 已经打开的modal
                        const modal = this.modalCtrl.getTop();
                        if (modal) {
                            (await modal).dismiss('success');
                        }
                        pageParams.type = res.params.pageType; // 蜂喔商户2.1.0 支持配置page或者modal
                    }
                    this.pageModalService.openPage(pageParams);
                } else if (skip === 0) {

                    //如果skip =0 并且target为null则刷新当前页面
                    if (res.target) {
                        let tmpParams = res.params;
                        if (localStorage.getItem('back_target') !== null) {
                            tmpParams = params.content;
                        }
                        const pageParams = {
                            type: "page",
                            target: res.target,
                            params: tmpParams,
                            sessionId: localStorage.getItem("sessionId")
                        };
                        this.pageModalService.openPage(pageParams);
                    } else {

                        this.eventService.eventEmit.emit(localStorage.getItem('tab'), '1');
                    }

                    const modal = this.modalCtrl.getTop();
                    if (modal) {
                        (await modal).dismiss('success');
                    }

                } else if (localStorage.getItem("isDetailPage") && skip === 0 && res.params.page_name === undefined) {

                    localStorage.setItem("needRefresh", "true");
                    this.appGlobalService.popTarget();
                    this.appGlobalService.goBack();

                } else if (skip && skip === 4) { // 跳转到模态窗口
                    // "是否跳转页面 0不跳/1跳"
                    const link = {
                        pageId: res.target,
                        params: res.params,
                        sessionId: localStorage.getItem("sessionId")
                        , type: 'modal'
                    };
                    this.pageModalService.openPage(link);
                } else {
                    localStorage.setItem("needRefresh", "true");
                    this.appGlobalService.goBack();
                }
            }


        } catch (error) {

        }
    }

    // 处理 员工 当前定位城市
    setPxwCityPosition(positionInfo) {
        if (this.appGlobalService.clientType === 'pxw') {
            // 如果有第一次城市信息，firstPostion === {}，存firstPostion
            const firstPostion = localStorage.getItem('firstPostion');
            if (!firstPostion) {
                localStorage.setItem('firstPostion', JSON.stringify(positionInfo));
                localStorage.setItem('position', JSON.stringify(positionInfo));
                // 通过城市名称设置经纬度
                this.mapBaiduService.getPointByName(positionInfo.name, (point) => {
                    positionInfo.center = { lng: point.lng, lat: point.lat };
                    localStorage.setItem('position', JSON.stringify(positionInfo));
                });
            }
        }
    }

    public jVerificationLogin(params, getPhoneSubmitId, loginSubmitId, callBackFunction) {
        this.http.post('application/page', params, res => {
            const loginData = JSON.parse(res.script);
            getPhoneSubmitId = loginData.data.preloadSubmit.id;
            loginSubmitId = loginData.data.button[0].submit.id; // button[0] 表示本机号码一键登录按钮  button[1] 表示其他手机号码登录
            this.appGlobalService.jVerificationAuth((msg) => {
                // 走原来的登陆流程
                if (msg === null) {
                    callBackFunction(); // 2024.07.17 防止插件报错导致无反应
                } else { // 极光登录
                    const resultObj = JSON.parse(msg);
                    // code: 返回码，6000代表loginToken获取成功，6001代表loginToken获取失败，其他返回码详见描述
                    // content：返回码的解释信息，若获取成功，内容信息代表loginToken。
                    // operator：成功时为对应运营商，CM代表中国移动，CU代表中国联通，CT代表中国电信。失败时可能为null
                    if (resultObj && resultObj.code === 6000) {
                        // 与后台联调submit接口
                        const params1 = {
                            id: loginSubmitId,
                            content: { token: resultObj.content },
                            sessionId: localStorage.getItem('sessionId')
                        };
                        if (loginData.data.button && loginData.data.button[0] && loginData.data.button[0].submit) {
                            loginData.data.button[0].submit.content['token'] = params1.content['token'];
                            params1.content = loginData.data.button[0].submit.content;
                        }
                        this.http.post("application/submit", params1, res1 => {
                            if (res1.success) {
                                // 登录成功
                                this.processLoginData(res1, res1.data.account ? res1.data.account : '', params1);
                            } else {
                                this.appGlobalService.showToast(res1.message, 2000, "middle");
                            }
                        });
                    } else {
                        // 极光的错误信息
                        // this.appGlobalService.showToast(resultObj.content, 2000, "middle");
                        // 走原来的登陆流程
                        // if(resultObj.code === 6002){ // 用户主动取消登录
                        callBackFunction(resultObj.code);
                        // }

                    }
                }
            }, loginData);
        });
    }

}
